//
//  AppDelegate.m
//  EDF
//
//  Created by p on 2019/7/4.
//  Copyright © 2019年 p. All rights reserved.
//

#import "AppDelegate.h"
#import "EDMainTabBarController.h"
#import "IQKeyboardManager.h"
#import "CoreNewFeatureVC.h"
#import "CheckVersionAlearView.h"

// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate
+ (AppDelegate *)shareAppdelegate
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
//横屏竖屏
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
    if (self.allowRotation == YES) {
        //横屏
        return UIInterfaceOrientationMaskLandscape;
        
    }else{
        //竖屏
        return UIInterfaceOrientationMaskPortrait;
        
    }
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] init];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.frame = [UIScreen mainScreen].bounds;
    
    //Required
       //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
       JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
       entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
       if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
         // 可以添加自定义 categories
         // NSSet<UNNotificationCategory *> *categories for iOS10 or later
         // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
       }
       [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
      
      // notice: 2.1.5 版本的 SDK 新增的注册方法，改成可上报 IDFA，如果没有使用 IDFA 直接传 nil  0（默认值）表示采用的是开发证书，1 表示采用生产证书发布应用。
      [JPUSHService setupWithOption:launchOptions appKey:@"a54e613205d0daa1bfc76ea1"
                            channel:@"app"
                   apsForProduction:1
              advertisingIdentifier:nil];
      
      [JPUSHService setDebugMode];
    
    
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES; // 控制整个功能是否启用。
    manager.shouldResignOnTouchOutside =YES; // 控制点击背景是否收起键盘
    //    manager.shouldToolbarUsesTextFieldTintColor =NO; // 控制键盘上的工具条文字颜色是否用户自定义
    manager.enableAutoToolbar =YES; // 控制是否显示键盘上的工具条
    //    manager.toolbarManageBehaviour =IQAutoToolbarByTag;
    [[IQKeyboardManager sharedManager] setToolbarManageBehaviour:IQAutoToolbarByPosition];
    //判断是否需要显示：（内部已经考虑版本及本地版本缓存）
    BOOL canShow = [CoreNewFeatureVC canShowNewFeature];
    
    if(canShow){
        NewFeatureModel *m1 = [NewFeatureModel model:[UIImage imageNamed:@"f1.png"]];
        NewFeatureModel *m2 = [NewFeatureModel model:[UIImage imageNamed:@"f2.png"]];
        NewFeatureModel *m3 = [NewFeatureModel model:[UIImage imageNamed:@"f3.png"]];
   
        if (KIsIPhoneX) {
            self.window.rootViewController = [CoreNewFeatureVC newFeatureVCWithModels:@[ [NewFeatureModel model:[UIImage imageNamed:@"x1.png"]], [NewFeatureModel model:[UIImage imageNamed:@"x2.png"]], [NewFeatureModel model:[UIImage imageNamed:@"x3.png"]],] enterBlock:^{
                NSLog(@"进入主页面");
              
                EDMainTabBarController * mainTab = [[EDMainTabBarController alloc]init];
                self.window.rootViewController =mainTab;
            }];
        }else{
            self.window.rootViewController = [CoreNewFeatureVC newFeatureVCWithModels:@[m1,m2,m3] enterBlock:^{
                NSLog(@"进入主页面");
          
                EDMainTabBarController * mainTab = [[EDMainTabBarController alloc]init];
                self.window.rootViewController =mainTab;
                
            }];
        }
        
    }else{
        EDMainTabBarController * mainTab = [[EDMainTabBarController alloc]init];
        self.window.rootViewController =mainTab;
        
    }
    

    
    [self performSelector:@selector(sendNotation:) withObject:launchOptions afterDelay:1.5];
    
    
    [self getVersion];
    [self.window makeKeyAndVisible];
    /*适配iOS11*/
    [UITableView appearance].estimatedRowHeight = 0;
    [UITableView appearance].estimatedSectionHeaderHeight = 0;
    [UITableView appearance].estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    return YES;
}
-(void)sendNotation:(NSDictionary *)launchOptions{
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0; //本地消息清0
    [JPUSHService setBadge:0];//极光消息清0
    
    if (launchOptions) {
        
        NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
        
        if (remoteNotification) {
            
            [self jumpToViewctroller:remoteNotification];
            
        }
        
    }
    
}
//获取应用当前版本号
- (NSString *)Version
{
    //此获取的版本号对应bundle，打印出来对应为12345这样的数字
    //    NSNumber *number = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
    
    //此获取的版本号对应version，打印出来对应为1.2.3.4.5这样的字符串
    NSString *string = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    return string;
}
- (void)getVersion
{
    
    WeakSelf
    NSString  * banber = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getAppVersionInfo"];
    [[SmileHttpTool sharedInstance] GET :banber parameters:@{@"type":@"ios"} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        if (!kStringIsEmpty(responseObject)) {
            NSDictionary * dic  = [self objectFromJSONString:responseObject];
            NSString * url = [dic jsonDict:@"data"][@"download_url"];
            NSString * force =[dic jsonDict:@"data"][@"force"]; //1为建议升级，2为强制升级
            NSString *  upgrade_point = [dic jsonDict:@"data"][@"text"]; //更新提示
            NSString *  Version = [self Version];
            NSString * version_code = [dic jsonDict:@"data"][@"version"];
            weakSelf.customer_service = [dic jsonDict:@"data"][@"customer_service"];
            BOOL isUpdata;
            //本地版本大于等于线上的，不需要提示更新，如果本地版本小于线上的，就需要提示更新
            if ([[Version stringByReplacingOccurrencesOfString:@"." withString:@""] floatValue] >= [[version_code stringByReplacingOccurrencesOfString:@"." withString:@""] floatValue] )
            {
                isUpdata = NO;
            }else
            {
                isUpdata = YES;
            }
            if ([Version isEqualToString:version_code]) {
                    isUpdata = NO;
            }
//            [weakSelf VersionupdateWithmessage:@"检测到 版本更新v1.21 现在要更新吗？" openUrl:url confirm:@"马上升级" cancel:nil state:1];
//            [weakSelf VersionupdateWithmessage:@"检测到 版本更新v1.21 现在要更新吗？" openUrl:url confirm:@"马上升级" cancel:@"我再想想" state:2];
            if (isUpdata) {
                
                if ([force isEqualToString:@"是"]) {
                    [weakSelf VersionupdateWithmessage:upgrade_point openUrl:url confirm:@"马上升级" cancel:nil state:1];
                }else
                {
                    [weakSelf VersionupdateWithmessage:upgrade_point openUrl:url confirm:@"马上升级" cancel:@"我再想想" state:2];
                    
                }
                
                
            }
            
        }
        
    } failure:^(id responseObject, NSError *error) {
        
    }];
}
- (void)VersionupdateWithmessage:(NSString *)message
                         openUrl:(NSString *)url
                         confirm:(NSString *)confirm
                          cancel:(NSString *)cancel
                           state:(NSInteger )state
{
    
    CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message  titleStr:@"版本更新" openUrl:url confirm:confirm cancel:cancel state:state RechargeBlock:^{
        
        if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
        {
            
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        }else
        {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        }
    }];
    [aleartVC showLXAlertView];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    #pragma mark  集成第四步: 上传设备deviceToken
    /// Required - 注册 DeviceToken
      [JPUSHService registerDeviceToken:deviceToken];

   
 
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
 
}

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
  if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //从通知界面直接进入应用
      
  }else{
    //从通知设置界面进入应用
  }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
      
      if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive ) {
             
             [self jumpToViewctroller:userInfo];
             
             [UIApplication sharedApplication].applicationIconBadgeNumber = 0; //本地消息清0
             
             [JPUSHService setBadge:0];//极光消息清0
             
         }
  }
  completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
      
      if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive ) {
             
             [self jumpToViewctroller:userInfo];
             
             [UIApplication sharedApplication].applicationIconBadgeNumber = 0; //本地消息清0
             
             [JPUSHService setBadge:0];//极光消息清0
             
         }
      
      
  }
  completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

  // Required, iOS 7 Support
  [JPUSHService handleRemoteNotification:userInfo];
    
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive ) {
        
        [self jumpToViewctroller:userInfo];
        
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        
        [JPUSHService setBadge:0];
        
    }
    
    
    
  completionHandler(UIBackgroundFetchResultNewData);
}
-(void)jumpToViewctroller:(NSDictionary *)remoteNotification{
YYLog(@"-remoteNotification-------%@",remoteNotification);
    
    
    
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

  // Required, For systems with less than or equal to iOS 6
  [JPUSHService handleRemoteNotification:userInfo];
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}





@end
